package cn.leftsite.netty.test.preset;

import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * 使用LengthFieldBasedFrameDecoder解码器基于长度的协议
 *
 * @author wangjinqiang
 * @date 2019-05-31
 */
public class LengthBaseInitializer extends ChannelInitializer<Channel> {
    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // 使用LengthFieldBaseFrameDecoder 解码， 将帧长度编码到帧起始的8个字节中的消息
        pipeline.addLast(new LengthFieldBasedFrameDecoder(64 * 1024, 0, 8));
        pipeline.addLast(new FrameHandler());
    }

    public static final class FrameHandler extends SimpleChannelInboundHandler<ByteBuf> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
            // 处理帧数据
        }
    }
}
